// 扫雷游戏类
class MinesweeperGame {
    constructor() {
        this.boardElement = document.getElementById('minesweeper-board');
        
        this.difficulties = {
            easy: { rows: 9, cols: 9, mines: 10 },
            medium: { rows: 16, cols: 16, mines: 40 },
            hard: { rows: 16, cols: 30, mines: 99 }
        };
        
        this.currentDifficulty = 'easy';
        this.board = [];
        this.revealed = [];
        this.flagged = [];
        this.gameStarted = false;
        this.gameEnded = false;
        this.startTime = 0;
        this.timer = null;
        this.minesLeft = 0;
        
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏板
    initBoard() {
        const config = this.difficulties[this.currentDifficulty];
        this.board = Array(config.rows).fill().map(() => Array(config.cols).fill(0));
        this.revealed = Array(config.rows).fill().map(() => Array(config.cols).fill(false));
        this.flagged = Array(config.rows).fill().map(() => Array(config.cols).fill(false));
        this.minesLeft = config.mines;
        this.gameStarted = false;
        this.gameEnded = false;
        this.firstClick = true;
        
        this.updateMinesLeft();
        this.createBoardHTML();
    }

    // 创建游戏板HTML
    createBoardHTML() {
        const config = this.difficulties[this.currentDifficulty];
        this.boardElement.innerHTML = '';
        this.boardElement.style.gridTemplateColumns = `repeat(${config.cols}, 25px)`;
        this.boardElement.style.gridTemplateRows = `repeat(${config.rows}, 25px)`;
        
        for (let row = 0; row < config.rows; row++) {
            for (let col = 0; col < config.cols; col++) {
                const cell = document.createElement('div');
                cell.className = 'mine-cell';
                cell.dataset.row = row;
                cell.dataset.col = col;
                
                cell.addEventListener('click', (e) => this.handleCellClick(e, row, col));
                cell.addEventListener('contextmenu', (e) => this.handleRightClick(e, row, col));
                cell.addEventListener('dblclick', (e) => this.handleDoubleClick(e, row, col));
                
                this.boardElement.appendChild(cell);
            }
        }
    }

    // 放置地雷
    placeMines(firstClickRow, firstClickCol) {
        const config = this.difficulties[this.currentDifficulty];
        let minesPlaced = 0;
        
        // 获取第一次点击周围的安全区域（3x3区域）
        const safeZone = [];
        for (let dr = -1; dr <= 1; dr++) {
            for (let dc = -1; dc <= 1; dc++) {
                const newRow = firstClickRow + dr;
                const newCol = firstClickCol + dc;
                if (this.isValidCell(newRow, newCol)) {
                    safeZone.push({ row: newRow, col: newCol });
                }
            }
        }
        
        while (minesPlaced < config.mines) {
            const row = Math.floor(Math.random() * config.rows);
            const col = Math.floor(Math.random() * config.cols);
            
            // 检查是否在安全区域内
            const isInSafeZone = safeZone.some(pos => pos.row === row && pos.col === col);
            
            if (this.board[row][col] !== -1 && !isInSafeZone) {
                this.board[row][col] = -1; // -1 表示地雷
                minesPlaced++;
            }
        }
        
        // 计算数字
        this.calculateNumbers();
    }

    // 计算数字
    calculateNumbers() {
        const config = this.difficulties[this.currentDifficulty];
        
        for (let row = 0; row < config.rows; row++) {
            for (let col = 0; col < config.cols; col++) {
                if (this.board[row][col] !== -1) {
                    let count = 0;
                    for (let dr = -1; dr <= 1; dr++) {
                        for (let dc = -1; dc <= 1; dc++) {
                            const newRow = row + dr;
                            const newCol = col + dc;
                            if (this.isValidCell(newRow, newCol) && this.board[newRow][newCol] === -1) {
                                count++;
                            }
                        }
                    }
                    this.board[row][col] = count;
                }
            }
        }
    }

    // 检查是否为有效单元格
    isValidCell(row, col) {
        const config = this.difficulties[this.currentDifficulty];
        return row >= 0 && row < config.rows && col >= 0 && col < config.cols;
    }

    // 开始游戏
    startGame() {
        this.initBoard();
        this.resetTimer();
    }

    // 处理单元格点击
    handleCellClick(e, row, col) {
        e.preventDefault();
        
        if (this.gameEnded || this.revealed[row][col]) {
            return;
        }
        
        // 如果格子被标记了，不能点击
        if (this.flagged[row][col]) {
            return;
        }
        
        if (!this.gameStarted) {
            this.gameStarted = true;
            this.firstClick = false;
            this.placeMines(row, col);
            this.startTimer();
        }
        
        this.revealCell(row, col);
    }

    // 处理右键点击（标记）
    handleRightClick(e, row, col) {
        e.preventDefault();
        
        if (this.gameEnded || this.revealed[row][col]) {
            return;
        }
        
        // 切换标记状态
        this.flagged[row][col] = !this.flagged[row][col];
        
        // 更新剩余地雷数（只是显示用，不影响游戏逻辑）
        this.minesLeft += this.flagged[row][col] ? -1 : 1;
        this.updateMinesLeft();
        this.updateCellDisplay(row, col);
    }

    // 揭示单元格
    revealCell(row, col) {
        if (!this.isValidCell(row, col) || this.revealed[row][col] || this.flagged[row][col]) {
            return;
        }
        
        this.revealed[row][col] = true;
        this.updateCellDisplay(row, col);
        
        if (this.board[row][col] === -1) {
            // 踩到地雷
            this.gameOver(false);
            return;
        }
        
        if (this.board[row][col] === 0) {
            // 空白区域，自动揭示周围
            for (let dr = -1; dr <= 1; dr++) {
                for (let dc = -1; dc <= 1; dc++) {
                    this.revealCell(row + dr, col + dc);
                }
            }
        }
        
        this.checkWin();
    }

    // 更新单元格显示
    updateCellDisplay(row, col) {
        const config = this.difficulties[this.currentDifficulty];
        const cellIndex = row * config.cols + col;
        const cell = this.boardElement.children[cellIndex];
        
        if (this.flagged[row][col]) {
            cell.className = 'mine-cell flagged';
            cell.textContent = '🚩';
        } else if (this.revealed[row][col]) {
            cell.className = 'mine-cell revealed';
            
            if (this.board[row][col] === -1) {
                cell.textContent = '💣';
                cell.classList.add('mine');
            } else if (this.board[row][col] > 0) {
                cell.textContent = this.board[row][col];
                cell.classList.add(`number-${this.board[row][col]}`);
            }
        } else {
            cell.className = 'mine-cell';
            cell.textContent = '';
        }
    }

    // 检查胜利
    checkWin() {
        const config = this.difficulties[this.currentDifficulty];
        let revealedCount = 0;
        let correctFlags = 0;
        let totalFlags = 0;
        
        for (let row = 0; row < config.rows; row++) {
            for (let col = 0; col < config.cols; col++) {
                if (this.revealed[row][col]) {
                    revealedCount++;
                }
                if (this.flagged[row][col]) {
                    totalFlags++;
                    if (this.board[row][col] === -1) {
                        correctFlags++;
                    }
                }
            }
        }
        
        const totalCells = config.rows * config.cols;
        
        // 胜利条件：所有非地雷格子都被揭开
        if (revealedCount === totalCells - config.mines) {
            this.gameOver(true);
        }
    }

    // 游戏结束
    async gameOver(won) {
        this.gameEnded = true;
        this.stopTimer();
        
        if (won) {
            const time = Math.floor((Date.now() - this.startTime) / 1000);
            await this.saveGameData(time);
            const data = await this.loadGameData();
            const difficultyKey = `bestTime_${this.currentDifficulty}`;
            const isNewRecord = time === data[difficultyKey];
            
            let message = `🎉 恭喜！你赢了！\n⏱️ 用时: ${time}秒\n🏆 最佳时间: ${data[difficultyKey]}秒`;
            if (isNewRecord) {
                message += '\n🌟 新纪录！';
            }
            alert(message);
        } else {
            // 显示所有地雷和错误标记
            const config = this.difficulties[this.currentDifficulty];
            for (let row = 0; row < config.rows; row++) {
                for (let col = 0; col < config.cols; col++) {
                    if (this.board[row][col] === -1) {
                        this.revealed[row][col] = true;
                        this.updateCellDisplay(row, col);
                    } else if (this.flagged[row][col]) {
                        // 标记错误的位置
                        const cellIndex = row * config.cols + col;
                        const cell = this.boardElement.children[cellIndex];
                        cell.classList.add('wrong-flag');
                    }
                }
            }
            alert('💥 游戏结束！你踩到了地雷！\n💡 提示：双击数字可以快速揭开周围格子');
        }
    }

    // 开始计时
    startTimer() {
        this.startTime = Date.now();
        this.timer = setInterval(() => {
            const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
            document.getElementById('minesweeper-time').textContent = elapsed;
        }, 1000);
    }

    // 停止计时
    stopTimer() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    // 重置计时器
    resetTimer() {
        this.stopTimer();
        document.getElementById('minesweeper-time').textContent = '0';
    }

    // 处理双击（快速揭开周围格子）
    handleDoubleClick(e, row, col) {
        e.preventDefault();
        
        if (this.gameEnded || !this.revealed[row][col] || this.board[row][col] === 0) {
            return;
        }
        
        // 计算周围标记的地雷数
        let flaggedCount = 0;
        for (let dr = -1; dr <= 1; dr++) {
            for (let dc = -1; dc <= 1; dc++) {
                const newRow = row + dr;
                const newCol = col + dc;
                if (this.isValidCell(newRow, newCol) && this.flagged[newRow][newCol]) {
                    flaggedCount++;
                }
            }
        }
        
        // 如果标记数等于该格子的数字，则揭开周围所有未标记的格子
        if (flaggedCount === this.board[row][col]) {
            for (let dr = -1; dr <= 1; dr++) {
                for (let dc = -1; dc <= 1; dc++) {
                    const newRow = row + dr;
                    const newCol = col + dc;
                    if (this.isValidCell(newRow, newCol) && 
                        !this.revealed[newRow][newCol] && 
                        !this.flagged[newRow][newCol]) {
                        this.revealCell(newRow, newCol);
                    }
                }
            }
        }
    }

    // 更新剩余地雷数
    updateMinesLeft() {
        document.getElementById('mines-left').textContent = this.minesLeft;
    }

    // 绑定事件
    bindEvents() {
        // 难度选择
        document.querySelectorAll('.difficulty-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.difficulty-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this.currentDifficulty = btn.dataset.difficulty;
                this.startGame();
            });
        });
    }

    // 保存游戏数据
    async saveGameData(time) {
        const currentData = await this.loadGameData();
        const difficultyKey = `bestTime_${this.currentDifficulty}`;
        const gameData = {
            ...currentData,
            [difficultyKey]: Math.min(time, currentData[difficultyKey] || Infinity),
            gamesPlayed: (currentData.gamesPlayed || 0) + 1,
            gamesWon: (currentData.gamesWon || 0) + 1
        };
        await authManager.saveGameData('minesweeper', gameData);
        await this.updateGameStats();
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('minesweeper') || {};
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        const difficultyKey = `bestTime_${this.currentDifficulty}`;
        const bestTime = data[difficultyKey];
        document.getElementById('best-time').textContent = bestTime && bestTime !== Infinity ? `${bestTime}s` : '--';
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let minesweeperGame;